package com.sy.core.shiro;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sy.core.model.SysMenu;
import com.sy.core.model.SysUser;
import com.sy.core.model.common.MenuTree;
import com.sy.core.model.common.Permissions;
import com.sy.core.service.SysMenuService;
import com.sy.core.service.SysRelationService;
import com.sy.core.service.SysUserService;
import com.sy.core.web.LoginCtl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class MmsRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRelationService sysRelationService;
    @Autowired
    private LoginCtl loginCtl;
    @Override
    public void setName(String name) {
        super.setName("MmsRealm");
    }
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取安全数据
        Object obj = principalCollection.getPrimaryPrincipal();
        Permissions permissions = new Permissions();
        if(obj instanceof Permissions) {
            permissions = (Permissions) obj;
        } else {
            permissions = JSON.parseObject(JSON.toJSON(obj).toString(), Permissions.class);
        }
        //2.获取权限信息
        Set<String> apiPerms = new HashSet();
        List<MenuTree> apis = permissions.getApis();
        for (int i = 0; i <apis.size() ; i++) {
            apiPerms.add(apis.get(i).getIndex());
        }
        //3.构造权限数据，返回值
        SimpleAuthorizationInfo info = new  SimpleAuthorizationInfo();
        info.setStringPermissions((Set<String>) apiPerms);
        return info;
    }

    /**
     * 认证方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取用户的手机号和密码
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String mobile = upToken.getUsername();
        String password = new String( upToken.getPassword());
        SysUser user = sysUserService.queryUserByPhoneAndPassword(mobile,password);
        if(user!=null){
            Permissions permissions = new Permissions();
            List<MenuTree> menus = getAuthorization(user.getRolePk(),"1");//功能类型1菜单2.按钮3.API
            List<MenuTree> points= getAuthorization(user.getRolePk(),"2");
            List<MenuTree> apis = getAuthorization(user.getRolePk(), "3");
            permissions.setMenus(menus);
            permissions.setPoints(points);
            permissions.setApis(apis);
            permissions.setSysUser(user);
            //构造方法：安全数据，密码，realm域名
            SimpleAuthenticationInfo info = new
                    SimpleAuthenticationInfo(permissions,user.getPassword(),this.getName());
            return info;
        }
        //返回null，会抛出异常，标识用户名和密码不匹配
        return null;
    }

    /**
     * 查询用户权限
     * @param rolePks
     * @return
     */
    public List<MenuTree> getAuthorization(String rolePks,String type){
        if(rolePks!=null){
            String[] rolePk = rolePks.split(",");
            List<MenuTree> menuTreeList = new ArrayList<>();//所有权限
            List<MenuTree> menuTreeList2=new ArrayList<>();//种类权限
            Set<String> set = new HashSet<>();
            for (int i = 0; i <rolePk.length ; i++) {
                List<String> menuPkList = sysRelationService.queryMenuPk(rolePk[i]);
                if(menuPkList.size()>0){
                    for (int j = 0; j <menuPkList.size() ; j++) {
                        set.add(menuPkList.get(j));
                    }
                }else{
                    return null;
                }
            }
            for(String str :set){
                MenuTree menuTree = new MenuTree();
                SysMenu sysMenu = sysMenuService.queryByPrimaryKey(str);
                menuTree.setPk(sysMenu.getPk());
                menuTree.setPcode(sysMenu.getPcode());
                menuTree.setIcon(sysMenu.getIcon());
                menuTree.setIndex(sysMenu.getUrl());
                menuTree.setTitle(sysMenu.getName());
                menuTree.setNum(sysMenu.getNum());
                menuTree.setType(sysMenu.getC1());
                menuTreeList.add(menuTree);
            }
            for (int i = 0; i <menuTreeList.size() ; i++) {
                if(menuTreeList.get(i).getType().equals(type)){
                    menuTreeList2.add(menuTreeList.get(i));
                }
            }
            return menuTreeList2;
        }else{
            return null;
        }
    }
}
